<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Response;
use Modules\Demo\Models\Demo;
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;


class DemoController extends Controller
{
    protected $logger;
    protected $caller;
    protected $requestId;

    public function __construct(Request $request)
    {
        $this->requestId = time().rand(10000, 99999);
        $this->logger = new Logger('demo');
        $logPath = storage_path('logs/demo.log');
        $this->logger->pushHandler(new RotatingFileHandler($logPath, 30));
        $request->request->add(['requestId' => $this->requestId]);
        $this->logger->info($request->path() . ' request', $request->all());
        $this->caller = $request->path();
    }

    /**
     * 更新
     * @param Request $request
     * @return JsonResponse
     */
    public function update(Request $request)
    {
        $id = $request->input('id');
        if (!$id) {
            return $this->response($this->caller, $this->requestId, 500, 'id不能为空');
        }
        try {
            $info = Demo::find($id);
            $info->json_arr = [
                'ids' => [1, 2, 3],
            ];
            $info->save();
            return $this->response($this->caller, $this->requestId, 200, '更新成功');
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage(), $e->getTrace());
            return $this->response($this->caller, $this->requestId, 500, '更新失败！');
        }
    }

    /**
     * 详情
     * @param Request $request
     * @return JsonResponse
     */
    public function info(Request $request)
    {
        $id = $request->input('id');
        if (!$id) {
            return $this->response($this->caller, $this->requestId, 500, 'id不能为空');
        }
        try {
            $info = Demo::find($id);
            if ($info) {
                $data = [
                    'id' => $info->id,
                    'name' => $info->name,
                    'content' => $info->content,
                    'createdAt' => $info->created_at->format('Y-m-d H:i:s'),
                    'oneFile' => $info->one_file[0]['response']['path'],
                    'manyFiles' => array_column(array_column($info->many_files, 'response'), 'path'),
                    'jsonArr' => $info->json_arr['ids'],
                ];
                return $this->response($this->caller, $this->requestId, 200, 'success', $data);
            }
            return $this->response($this->caller, $this->requestId, 500, '内容不存在');
        } catch (\Exception $e) {
            $this->logger->error($e->getMessage(), $e->getTrace());
            return $this->response($this->caller, $this->requestId, 500, '内容不存在！');
        }
    }

    /**
     * 列表
     * @param Request $request
     * @return JsonResponse
     */
    public function list(Request $request)
    {
        $jsonArr = (int)$request->input('jsonArr');
        $page = Demo::where('status', 1)
            ->when($jsonArr, function ($query, $jsonArr) {
                $query->whereJsonContains('json_arr->ids', $jsonArr);
            })
            ->orderBy('id', 'desc')
            ->paginate();
        $list = [];
        foreach ($page->items() as $item) {
            $contentText = trim(preg_replace('/\s+/', ' ', strip_tags($item->content)));
            $shortText = mb_strlen($contentText) > 100 ? mb_substr($contentText, 0, 100) . '...' : $contentText;
            $list[] = [
                'id' => $item->id,
                'name' => $item->name,
                'contentShort' => $shortText,
                'createdAt' => $item->created_at->format('Y-m-d H:i:s'),
                'jsonArr' => $item->json_arr,
            ];
        }
        $data = custom_paginate($page, $list);
        return $this->response($this->caller, $this->requestId, 200, 'success', $data);
    }
}
